package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoMessageEvent;
import com.rw.coco.handler.message.reply.ReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.handler.message.reply.handler.command.sender.STSender;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;
import com.rw.tool.util.string.StringScanner;
import com.rw.tool.util.string.StringUtil;

import java.util.regex.Pattern;

/**
 * 设置属性
 * .st
 */
public class STHandler implements ReplyHandler {
    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    // 删除指令
    private static final Pattern DEL = Pattern.compile("del", Pattern.CASE_INSENSITIVE);

    // 清除指令
    private static final Pattern CLR = Pattern.compile("clr", Pattern.CASE_INSENSITIVE);

    // 展示指令
    private static final Pattern SHOW = Pattern.compile("show", Pattern.CASE_INSENSITIVE);

    public STHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String command = cocoCommandConfig.commandProp.get(CocoCommandConfig.ST);
        this.matcher = CommandMatcher.of(command);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_ST);
    }

    @Override
    public boolean trigger(CocoMessageEvent cocoMessageEvent) {
        String message = cocoMessageEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    public void handler(CocoMessageEvent cocoMessageEvent) {
        // 去掉st前缀，去掉所有空格字符和换行符
        String message = matcher.subBlank(cocoMessageEvent.getMessage());

        // 如果指令字符串为空，则返回信息
        if (StringUtil.isBlank(message)) {
            DiceReply diceReply = cocoMessageEvent.getReplyApi().getDiceReply();
            cocoMessageEvent.sendBack(diceReply.setPropEmpty(cocoMessageEvent));
            return;
        }

        // 设置属性，创建属性解析器
        STSender sender = new STSender(cocoMessageEvent);
        // 创建字符串扫描器
        StringScanner scanner = new StringScanner(message);
        if (scanner.hasNext(DEL)) {
            // 删除属性
            scanner.next(DEL);
            String propName = scanner.nextAll().trim();
            sender.deleteProp(propName);
        } else if (scanner.hasNext(CLR)) {
            // 清空属性
            sender.clearProp();
        } else if (scanner.hasNext(SHOW)) {
            scanner.next(SHOW);
            String propName = scanner.nextAll().trim();
            sender.show(propName);
        } else {
            // 如果解析属性成功，则属性入库，方法内已经附带了回复
            sender.parseAndSaveCocoProp(message);
        }
    }

    @Override
    public int priority() {
        return matcher.priority();
    }
}
